package com.bndg.browser.ui

import android.content.BroadcastReceiver
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import android.view.KeyEvent
import android.view.View
import androidx.fragment.app.FragmentManager
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import com.blankj.utilcode.util.RegexUtils
import com.bndg.browser.ActivityManager
import com.bndg.browser.MainActivity
import com.bndg.browser.R
import com.bndg.browser.bean.VideoBean
import com.bndg.browser.client.AndroidInterface
import com.bndg.browser.fargment.AgentWebFragment
import com.bndg.browser.fargment.FragmentKeyDown
import com.bndg.browser.util.OtherUtils
import com.bndg.browser.util.Trace
import com.hjq.base.BaseActivity
import com.hjq.base.BaseDialog
import com.hjq.demo.ui.dialog.BottomMediaDialog
import com.hjq.demo.ui.dialog.BottomMenuDialog
import java.util.ArrayList


/**
 * Created by cenxiaozhong on 2017/5/23.
 * source code  https://github.com/Justson/AgentWeb
 */
class CommonActivity : BaseActivity() {
    private val mDetectedVideoReceiver: BroadcastReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: android.content.Context?, intent: Intent?) {
            intent?.let { intent1 ->
                if (intent1.action == AndroidInterface.ACTION_DETECTED_VIDEO) {
                    val videos = intent1.getStringArrayListExtra("videos")
                    if (!videos.isNullOrEmpty()) {
                        val mediaInfos = mutableListOf<BottomMediaDialog.MediaInfo>()
                        for (video in videos) {
                            val videoInfo = BottomMediaDialog.MediaInfo(video)
                            mediaInfos.add(videoInfo)
                        }
                        showVideoFab(mediaInfos)
                    }
                } else if (intent1.action == AndroidInterface.VIDEO_BEAN) {
                    val videoBean =
                        intent1.getParcelableExtra<VideoBean>(AndroidInterface.VIDEO_BEAN)
                    videoBean?.let {
                        val mediaInfos = mutableListOf<BottomMediaDialog.MediaInfo>()
                        val mediaInfo = BottomMediaDialog.MediaInfo(it.videoUrl ?: "", it.title)
                        mediaInfos.add(mediaInfo)
                        showVideoFab(mediaInfos)
                    }
                }

            }
        }
    }
    private var mediaDialogBuilder: BottomMediaDialog.Builder? = null
    private fun showVideoFab(videos: MutableList<BottomMediaDialog.MediaInfo>) {
        Trace.d(">>>>", "需要显示fab : $videos")
        fabVideo?.visibility = View.VISIBLE
        fabVideo?.setOnClickListener {
            if (mediaDialogBuilder == null) {
                mediaDialogBuilder = BottomMediaDialog.Builder(this)
                    .setListener(object : BottomMediaDialog.OnListener {
                        override fun onSelected(
                            dialog: BaseDialog?,
                            position: Int,
                            bean: BottomMediaDialog.MediaInfo
                        ) {
                            val intent =
                                Intent(this@CommonActivity, LocalVideoPlayActivity::class.java)
                            intent.putExtra(LocalVideoPlayActivity.VIDEO_URL, bean.url)
                            startActivity(intent)
                        }
                    })
            }
            mediaDialogBuilder?.addData(videos)
            mediaDialogBuilder?.show()
        }
    }

    private lateinit var currentUrl: String
    private var mFragmentManager: FragmentManager? = null
    private val ivBack: View? by lazy { findViewById<View>(R.id.iv_back) }
    private val ivForward: View? by lazy { findViewById<View>(R.id.iv_forward) }
    private val ivMenu: View? by lazy { findViewById<View>(R.id.iv_menu) }
    private val ivTags: View? by lazy { findViewById<View>(R.id.iv_tags) }
    private val ivHome: View? by lazy { findViewById<View>(R.id.iv_home) }
    private val fabVideo: View? by lazy { findViewById<View>(R.id.fab_video) }

    override fun getLayoutId(): Int {
        return R.layout.common_activity
    }

    override fun initView() {
//        ImmersionBar.with(this).keyboardEnable(true).statusBarView(findViewById(R.id.view_top)).init()
        val content = intent.getStringExtra("input")
        content?.let { inputContent ->
            if (RegexUtils.isURL(inputContent) || RegexUtils.isIP(inputContent)) {
                currentUrl = inputContent
            } else {
                if (RegexUtils.isMatch(
                        "^[a-zA-Z0-9-]+(\\.[a-zA-Z0-9-]+)*\\.[a-zA-Z]{2,}\$",
                        inputContent
                    )
                ) {
                    // 如果符合格式且没有协议头，则添加 "https://"
                    if (!inputContent.startsWith("http://") && !inputContent.startsWith("https://")) {
                        currentUrl = "https://$inputContent"
                    } else {
                        currentUrl =
                            "https://cn.bing.com/search?q=$inputContent&form=QBLH&sp=-1&lq=0&pq=&sc=10-0&qs=n&sk=&cvid=94420EE6C69F4046815C2440000041E9"
                    }
                } else {
                    currentUrl =
                        "https://cn.bing.com/search?q=$inputContent&form=QBLH&sp=-1&lq=0&pq=&sc=10-0&qs=n&sk=&cvid=94420EE6C69F4046815C2440000041E9"
                }
            }
            mFragmentManager = this.supportFragmentManager
            val ft = mFragmentManager!!.beginTransaction()
            var mBundle: Bundle? = null
            ft.add(
                R.id.container_framelayout,
                AgentWebFragment.getInstance(Bundle().also { mBundle = it })
                    .also { mAgentWebFragment = it },
                AgentWebFragment::class.java.name
            )
            mBundle!!.putString(AgentWebFragment.URL_KEY, currentUrl)
            ft.commit()
        }
        setOnClickListener(ivBack, ivForward, ivMenu, ivTags, ivHome)
        val intentFilter = IntentFilter()
        intentFilter.addAction(AndroidInterface.ACTION_DETECTED_VIDEO)
        intentFilter.addAction(AndroidInterface.VIDEO_BEAN)
        LocalBroadcastManager.getInstance(this).registerReceiver(
            mDetectedVideoReceiver,
            intentFilter
        )
    }

    override fun onClick(view: View) {
        if (view.id == R.id.iv_back) {
            mAgentWebFragment?.let {
                it.canBack()
            }
        } else if (view.id == R.id.iv_forward) {
            mAgentWebFragment?.let {
                it.canForward()
            }
        } else if (view.id == R.id.iv_menu) {
            // 弹出bottomsheet 菜单
            showBottomSheetDialog()
        } else if (view.id == R.id.iv_tags) {
        } else if (view.id == R.id.iv_home) {
            ActivityManager.getInstance().finishAllActivities(MainActivity::class.java)
        }
    }

    private fun showBottomSheetDialog() {
        if (OtherUtils.isDoubleClick()) {
            return
        }
        BottomMenuDialog.Builder(this)
            .setListener(object : BottomMenuDialog.OnListener {
                override fun onSelected(
                    dialog: BaseDialog?,
                    position: Int,
                    bean: BottomMenuDialog.MenuInfo
                ) {
                    if (bean.isHistory()) {
                        startActivity(Intent(this@CommonActivity, HistoryActivity::class.java))
                    }
                }
            })
            .show()
    }

    /**
     * 初始化数据
     */
    override fun initData() {

    }

    private var mAgentWebFragment: AgentWebFragment? = null

    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        val mAgentWebFragment = this.mAgentWebFragment
        if (mAgentWebFragment != null) {
            val mFragmentKeyDown: FragmentKeyDown = mAgentWebFragment
            return if (mFragmentKeyDown.onFragmentKeyDown(keyCode, event)) {
                true
            } else {
                super.onKeyDown(keyCode, event)
            }
        }
        return super.onKeyDown(keyCode, event)
    }

    override fun onDestroy() {
        super.onDestroy()
        LocalBroadcastManager.getInstance(this).unregisterReceiver(mDetectedVideoReceiver)
    }
}
